package com.powernode.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.powernode.client.UserClient;
import com.powernode.commons.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/web")
//@DefaultProperties(defaultFallback = "fallback")
public class UserController {

    //使用feign后就不需要RestTemplate
//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;

//    @Autowired
//    private DiscoveryClient discoveryClient;
    @HystrixCommand(
            fallbackMethod = "fallback",
            commandProperties = {
                @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="4000"),
                @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10")
    })
    @RequestMapping("/items")
    public Result findByList(){

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-server");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        Result result = restTemplate.getForObject("http://"+host+":"+port+"/user/items", Result.class);
//        Result result = restTemplate.getForObject("http://user-server/user/items", Result.class);

        Result result = userClient.findByList();
        return result;
    }

    /**
     * 熔断方法
     *  熔断方法返回值必须和主方法返回值保持一致, 形参保持一致, 方法名字可以自定义
     *  如果在类上 添加注解 @DefaultProperties(fallback="熔断方法名"), 则可以不用考虑形成, 直接定义无参方法即可
     * @return
     */
    public Result fallback(){
        return new Result(500,"服务失败，请稍后重试。。。");
    }
}
